package com.rd.project.service;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Stefan
 */
@Stateless
public class ExporteerServiceImpl implements ExporteerService {

    @Override
    public void genereerPdfTest(int testId)
            throws DocumentException, IOException {
        //Maak een nieuw document aan
        Document document = new Document();
        
        //Temp file aanmaken
        File temp = File.createTempFile("test", ".pdf");
        
        //PDF Genereren
        PdfWriter.getInstance(document, new FileOutputStream(temp.getAbsolutePath()));
        
        //Document openen
        document.open();
        
        //Inhoud toevoegen
        document.add(new Paragraph("Hello World!"));
        
        //Document sluiten
        document.close();
        
        
    }

    @Override
    public void genereerPdfKlas(int klasId)
            throws DocumentException, IOException {
        
    }
    
    @Override
    public void genereerPdfVak(int vakId)
            throws DocumentException, IOException {
    }
    
    public void exportPdf(File temp) throws FileNotFoundException, IOException {
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.setHeader("Content-Disposition", "attachment; filename=score.pdf");
        response.setContentLength((int) temp.length());
        
        ServletOutputStream out = null;
        
        FileInputStream input = new FileInputStream(temp);
        byte[] buffer = new byte[1024];
        out = response.getOutputStream();
        int i = 0;
        while((i = input.read(buffer)) != -1) {
            out.write(buffer);
            out.flush();
        }
        
        fc.responseComplete();
    }
}
